{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "67b0fda4-580f-42af-b7e6-3c7795bd7c41",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    feature_1  feature_2  feature_3  feature_4  feature_5 category\n",
      "0    0.065613  -1.814317  -0.848534   0.278723  -1.898162        A\n",
      "1    1.943645  -0.781251  -0.780406  -1.020383  -0.176647        A\n",
      "2    2.215437  -1.591460  -1.754176  -0.157724   0.875586        B\n",
      "3    2.248896   1.438831   1.071276   0.166088  -0.733065        A\n",
      "4    1.398888   1.603281   1.307294  -2.452265  -0.763596        A\n",
      "5   -1.562880  -0.144974   0.273727   1.516233  -0.682093        B\n",
      "6   -2.626884  -1.101402  -0.391544  -0.086414  -0.520867        A\n",
      "7    1.409785  -0.164145   0.110883   0.970524  -1.351649        B\n",
      "8    0.947384  -1.151891  -1.432692   1.859967   1.437839        B\n",
      "9    2.395492   2.780528   2.205731  -0.342309  -1.106124        B\n",
      "10        NaN  -2.187827  -2.298096   0.976309   1.656570        B\n",
      "11        NaN   1.992259   1.445123  -1.368590  -0.856359        A\n",
      "12        NaN  -2.332309  -2.882397   0.473627   3.167356        A\n",
      "13        NaN  -0.740383  -0.701945  -0.048195   1.537266        B\n",
      "14        NaN  -0.480863   0.028478   1.154354  -0.517866        A\n",
      "缺失值统计：\n",
      "feature_1    5\n",
      "feature_2    0\n",
      "feature_3    0\n",
      "feature_4    0\n",
      "feature_5    0\n",
      "category     0\n",
      "dtype: int64\n",
      "   feature_1  feature_2  feature_3  feature_4  feature_5 category\n",
      "0   0.065613  -1.814317  -0.848534   0.278723  -1.898162        A\n",
      "1   1.943645  -0.781251  -0.780406  -1.020383  -0.176647        A\n",
      "2   2.215437  -1.591460  -1.754176  -0.157724   0.875586        B\n",
      "3   2.248896   1.438831   1.071276   0.166088  -0.733065        A\n",
      "4   1.398888   1.603281   1.307294  -2.452265  -0.763596        A\n",
      "   feature_1  feature_2  feature_3  feature_4  feature_5 category\n",
      "0   0.024800  -1.141719  -0.422532   0.096350  -1.760035        A\n",
      "1   1.338669  -0.315537  -0.358630  -1.216473  -0.392620        A\n",
      "2   1.528815  -0.963492  -1.272003  -0.344705   0.443178        B\n",
      "3   1.552223   1.459948   1.378205  -0.017474  -0.834588        A\n",
      "4   0.957558   1.591465   1.599585  -2.663472  -0.858839        A\n",
      "   feature_1  feature_2  feature_3  feature_4  feature_5 category\n",
      "0   0.620964   0.346066   0.352165   0.577617   0.086161        A\n",
      "1   0.892221   0.472335   0.363961   0.302850   0.384983        A\n",
      "2   0.931478   0.373305   0.195352   0.485306   0.567631        B\n",
      "3   0.936311   0.743691   0.684581   0.553794   0.288399        A\n",
      "4   0.813538   0.763791   0.725448   0.000000   0.283100        A\n",
      "   feature_1  feature_2  feature_3  feature_4  feature_5  category_A  \\\n",
      "0   0.620964   0.346066   0.352165   0.577617   0.086161         1.0   \n",
      "1   0.892221   0.472335   0.363961   0.302850   0.384983         1.0   \n",
      "2   0.931478   0.373305   0.195352   0.485306   0.567631         0.0   \n",
      "3   0.936311   0.743691   0.684581   0.553794   0.288399         1.0   \n",
      "4   0.813538   0.763791   0.725448   0.000000   0.283100         1.0   \n",
      "\n",
      "   category_B  \n",
      "0         0.0  \n",
      "1         0.0  \n",
      "2         1.0  \n",
      "3         0.0  \n",
      "4         0.0  \n",
      "训练集大小： (80,)\n",
      "测试集大小： (20,)\n",
      "解释方差比例: [7.21475567e-01 1.02923490e-01 7.85631012e-02 5.77915646e-02\n",
      " 3.91799655e-02 6.63114994e-05]\n",
      "总解释方差: [0.72147557 0.82439906 0.90296216 0.96075372 0.99993369 1.        ]\n",
      "\n",
      "模型准确率： 0.8\n",
      "\n",
      "分类报告：\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.83      0.62      0.71         8\n",
      "           1       0.79      0.92      0.85        12\n",
      "\n",
      "    accuracy                           0.80        20\n",
      "   macro avg       0.81      0.77      0.78        20\n",
      "weighted avg       0.80      0.80      0.79        20\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.datasets    import    make_classification\n",
    "from sklearn.model_selection     import     train_test_split\n",
    "from sklearn.preprocessing   import  StandardScaler,   MinMaxScaler,  OneHotEncoder\n",
    "from sklearn.feature_selection    import   VarianceThreshold\n",
    "from sklearn.decomposition import PCA\n",
    "from  sklearn.impute  import  SimpleImputer\n",
    "from sklearn.linear_model   import   LogisticRegression\n",
    "from sklearn.metrics    import  accuracy_score,   classification_report\n",
    "#生成一个包含数值特征和类别特征的示例数据集\n",
    "X,y  =make_classification(n_samples=100,n_features=5,n_informative=3,n_redundant=1,random_state=42)\n",
    "#将数值特征转换为DataFrame\n",
    "df=pd.DataFrame(X,columns=['feature_1','feature_2','feature_3','feature_4','feature_5'])\n",
    "#添加一些缺失值\n",
    "df.iloc[10:15,0]=np.nan\n",
    "#添加一个类别特征\n",
    "df['category']=np.random.choice(['A','B'],size=100)\n",
    "#查看数据集\n",
    "print(df. head(15))\n",
    "# 检 测 缺 失 值\n",
    "missing_values   =  df.isnull().sum()\n",
    "print(\"缺失值统计：\")\n",
    "print(missing_values)\n",
    "#均值数填充数值特征\n",
    "imputer_cat   =  SimpleImputer ( strategy  ='mean')\n",
    "df[['feature_1']]=imputer_cat.fit_transform(df[['feature_1']])\n",
    "#众数填充类别特征\n",
    "#imputer_cat=SimpleImputer(strategy='most_frequent') #df[['feature_ 1']]=imputer_cat.fit_transform(df[['feature_ 1']])\n",
    "# 查 看 填 充 后 的 数 据\n",
    "print(df.head())\n",
    "# Initialize the scaler\n",
    "scaler = StandardScaler()\n",
    "# Standardize the features\n",
    "df[['feature_1', 'feature_2', 'feature_3', 'feature_4', 'feature_5']] = scaler.fit_transform(df[['feature_1', 'feature_2', 'feature_3', 'feature_4', 'feature_5']])\n",
    "print(df.head())\n",
    "from sklearn.preprocessing import MinMaxScaler\n",
    "normalizer = MinMaxScaler()\n",
    "df[['feature_1', 'feature_2', 'feature_3', 'feature_4', 'feature_5']] = normalizer.fit_transform(df[['feature_1', 'feature_2', 'feature_3', 'feature_4', 'feature_5']])\n",
    "print(df.head())\n",
    " #对类别特征进行One-Hot编码\n",
    "# 初始化OneHotEncoder，设置sparse_output=False以返回稠密矩阵\n",
    "encoder = OneHotEncoder(sparse_output=False)\n",
    "# 对'category'列进行One-Hot编码\n",
    "encoded_categories = encoder.fit_transform(df[['category']])\n",
    "# 将编码后的特征转换为DataFrame，并为每个编码列命名\n",
    "encoded_df = pd.DataFrame(encoded_categories, columns=encoder.get_feature_names_out(['category']))\n",
    "# 将编码后的特征与原始数据合并，删除原始的'category'列\n",
    "df = pd.concat([df.drop('category', axis=1), encoded_df], axis=1)\n",
    "# 查看编码后的数据\n",
    "print(df.head())\n",
    " #将数据集分为训练集和测试集\n",
    "# 假设 df 和 y 已经被定义并且是你数据的输入和目标变量\n",
    "X_train, X_test, y_train, y_test = train_test_split(df, y, test_size=0.2, random_state=42)\n",
    "\n",
    "# 查看分割后的数据\n",
    "print(\"训练集大小：\", y_train.shape)\n",
    "print(\"测试集大小：\", y_test.shape)\n",
    "# 创建 PCA 对象\n",
    "pca = PCA(n_components=6)\n",
    "# 对训练集和测试集进行PCA变换\n",
    "X_train_pca = pca.fit_transform(X_train)\n",
    "X_test_pca = pca.transform(X_test)\n",
    "# 定义PCA列名\n",
    "pca_columns = [f'PC{i+1}' for i in range(pca.n_components_)]\n",
    "# 将降维后的数据转换为DataFrame\n",
    "X_train_pca_df = pd.DataFrame(X_train_pca, columns=pca_columns)\n",
    "X_test_pca_df = pd.DataFrame(X_test_pca, columns=pca_columns)\n",
    "# 查看各主成分的解释方差比例\n",
    "print(\"解释方差比例:\", pca.explained_variance_ratio_)\n",
    "# 如果你需要查看总解释方差（即前6个主成分的累计贡献）\n",
    "print(\"总解释方差:\", np.cumsum(pca.explained_variance_ratio_))\n",
    "model=LogisticRegression(random_state=42)\n",
    "model.fit ( X_train,y_train )\n",
    "#在测试集上进行预测\n",
    "y_pred= model. predict(X_test )\n",
    "#评估模型性能\n",
    "print(\"\\n模型准确率：\",accuracy_score(y_test,y_pred))\n",
    "print(\"\\n分类报告：\")\n",
    "print(classification_report(y_test,y_pred))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7919f092-8194-452e-9892-5f725381359d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
